package com.example.teachingevaluationsystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.teachingevaluationsystem.entity.PlanTopic;
import com.example.teachingevaluationsystem.entity.Topic;
import com.example.teachingevaluationsystem.service.PlanTopicService;
import com.example.teachingevaluationsystem.service.TopicService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 评价题目 前端控制器
 *
 * @author lp
 * @since 2022-04-04
 */
@RestController
@RequestMapping("/evaluate/topic")
public class TopicController {

  @Autowired private TopicService topicService;
  @Autowired private PlanTopicService planTopicService;
  /**
   * 获取分页信息
   *
   * @return
   */
  @GetMapping("page")
  public Page<Topic> page(Page<Topic> topicPage) {
    return topicService.page(topicPage, new LambdaQueryWrapper<Topic>().orderByAsc(Topic::getId));
  }

  /** 查询题目详细信息 */
  @GetMapping("{topicId}")
  public Topic getTopicById(@PathVariable("topicId") Long topicId) {
    return topicService.getById(topicId);
  }

  /** 通过id删除题目 */
  @DeleteMapping
  public boolean deleteByIds(@RequestBody Long[] ids) {
    return topicService.removeBatchByIds(Arrays.asList(ids));
  }

  /** 保存或者更新题目 */
  @PostMapping
  public boolean save(@RequestBody Topic topic) {
    return topicService.saveOrUpdate(topic);
  }

  @GetMapping
  public List<Topic> list(String query) {
    LambdaQueryWrapper<Topic> topicLambdaQueryWrapper = new LambdaQueryWrapper<>();
    if(StringUtils.isNotBlank(query)){
      topicLambdaQueryWrapper.like(Topic::getTitle, query);
    }
    return topicService.list(topicLambdaQueryWrapper);
  }

  /** 查询评价计划中的题目 */
  @GetMapping("plan")
  public List<Topic> list(Long planId) {
    List<Long> topicIds =
        planTopicService
            .list(new LambdaQueryWrapper<PlanTopic>().eq(PlanTopic::getPlanId, planId))
            .stream()
            .map(PlanTopic::getTopicId)
            .toList();
    if (topicIds.isEmpty()) {
      return new ArrayList<>();
    }
    return topicService.list(new LambdaQueryWrapper<Topic>().in(Topic::getId, topicIds));
  }
}
